//
//  YWSelectApartmentTableViewController.m
//  maintain
//
//  Created by Kyo on 16/9/19.
//  Copyright © 2016年 ewin. All rights reserved.
//

#import "YWSelectApartmentTableViewController.h"
#import "UIColor+CustomColors.h"
#import "YWCommonTool.h"
#import "YWMacro.h"
#import "YWConst.h"
#import "YWLoginTool.h"

#import "YWApartment.h"
#import "YWBuilding.h"
#import "YWBuildingManager.h"

@interface YWSelectApartmentTableViewController (){
    YWApartment *selectedApartment;
    NSIndexPath *lastIndexPath;
}
@property (nonatomic, strong) NSArray *allApartments;
@end

@implementation YWSelectApartmentTableViewController
- (instancetype)init{
    return  [super initWithStyle:UITableViewStyleGrouped];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    NSString *apartmentShowName = [YWLoginTool apartmentShowName];
    self.title = [NSString stringWithFormat:@"%@%@",NSLocalizedString(@"select", nil),apartmentShowName.length?apartmentShowName:NSLocalizedString(@"apartment", nil)];
    [self initTableView];
    
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:NSLocalizedString(@"finish", nil) style:UIBarButtonItemStylePlain target:self action:@selector(rightBarButtonItemEvent:)];
}

- (void)initTableView{
    self.tableView.backgroundColor = [UIColor customBackgroudColor];
    self.tableView.separatorColor = [UIColor customLineColor];
    self.tableView.rowHeight = 44.0f;
    self.tableView.tableFooterView = [[UIView alloc]init];
    if (_canEdit) {
        UILabel *headLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 20, SCREEN_WIDTH, 44)];
        headLabel.font = kContentFont;
        headLabel.text = [NSString stringWithFormat:@"     %@",NSLocalizedString(@"newlyBuild", nil)];
        headLabel.userInteractionEnabled = YES;
        headLabel.backgroundColor = [UIColor whiteColor];
        [headLabel addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(clickHeadLabelEvent:)]];
        UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 84)];
        view.backgroundColor = [UIColor customBackgroudColor];
        [view addSubview:headLabel];
        self.tableView.tableHeaderView = view;
    }
    [self.tableView setEditing:YES];
}

- (NSArray *)allApartments{
    if (!_allApartments) {
        if (_lineId>0) {
            _allApartments = [[NSArray alloc] initWithArray:[[YWBuildingManager shareManager] apartmentArrayWithBuildingId:self.building.buildingId LineId:_lineId type:_isKeepWatch lineType:_isEquipmentLine]];
        }else if (_missionId >0){
            _allApartments = [[YWBuildingManager shareManager] selectPositionWithMissionId:_missionId equipmentTypeId:_equipmentTypeId positionType:2 buildingId:self.building.buildingId apartmentId:0 floorId:0];
        }else{
            _allApartments = [[NSArray alloc] initWithArray:[[YWBuildingManager shareManager] apartmentWithbuildingId:self.building.buildingId]];
        }
    }
    return _allApartments;
}
- (void)setOwnApartment:(YWApartment *)ownApartment{
    _ownApartment = ownApartment;
    if (ownApartment.apartmentId>0) {
        [self.allApartments enumerateObjectsUsingBlock:^(YWApartment*  _Nonnull apartment, NSUInteger idx, BOOL * _Nonnull stop) {
            if (apartment.apartmentId == ownApartment.apartmentId) {
                selectedApartment = apartment;
                *stop = YES;
            }
        }];
    }
}

#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.allApartments.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *cellIdentifier = @"YWSelectApartmentTableVCReuseIdentifier";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
        cell.textLabel.font = kContentFont;
    }
    YWApartment *apartment = self.allApartments[indexPath.row];
    cell.textLabel.text = apartment.apartmentName?:@"";
    return cell;
}

-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath{
    YWApartment *apartment = self.allApartments[indexPath.row];
    if (apartment.apartmentId == selectedApartment.apartmentId) {
        [tableView selectRowAtIndexPath:indexPath animated:NO scrollPosition:UITableViewScrollPositionNone];
    }else{
        [tableView deselectRowAtIndexPath:indexPath animated:NO];
    }
}

- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return UITableViewCellEditingStyleDelete | UITableViewCellEditingStyleInsert;
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    YWApartment *apartment = self.allApartments[indexPath.row];
    if (apartment.apartmentId != selectedApartment.apartmentId) {
        selectedApartment = apartment;
    }
    if (lastIndexPath) {
        [tableView deselectRowAtIndexPath:lastIndexPath animated:NO];
    }else{
        [self.tableView reloadData];
    }
    lastIndexPath = indexPath;
}

- (void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath{
    YWApartment *apartment = self.allApartments[indexPath.row];
    if (apartment.apartmentId == selectedApartment.apartmentId) {
        selectedApartment = nil;
    }
    lastIndexPath = nil;
}

- (void)clickHeadLabelEvent:(id)sender{
    //新增楼栋
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"newlyBuild", nil) message:nil preferredStyle:UIAlertControllerStyleAlert];
    [alert addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {
        textField.clearButtonMode = UITextFieldViewModeWhileEditing;
        textField.placeholder = NSLocalizedString(@"pleaseEnter", nil);//@"请输入";
    }];
    [alert addAction:[UIAlertAction actionWithTitle:NSLocalizedString(@"cancel", nil) style:UIAlertActionStyleDefault handler:nil]];
    [alert addAction:[UIAlertAction actionWithTitle:NSLocalizedString(@"sure", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        UITextField *textField = alert.textFields.firstObject;
        NSString *apartmentName = [textField.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
        if ([YWCommonTool isContainsEmoji:apartmentName]) {
            [YWCommonTool showTextHUDWithContent:NSLocalizedString(kTextCantContainEmoji, nil)];
        }else if (apartmentName.length==0){
            [YWCommonTool showTextHUDWithContent:NSLocalizedString(@"pleaseEnterSomething", nil)];
        }else if (apartmentName.length>20){
            [YWCommonTool showTextHUDWithContent:NSLocalizedString(@"contentLengthMustBeLessThan20", nil)];
        }else{
            if ([self.delegate respondsToSelector:@selector(popSelectedApartment:)]) {
                YWApartment *newApartment = [[YWApartment alloc] init];
                newApartment.apartmentId = - [YWCommonTool randNumber];
                newApartment.apartmentName = apartmentName;
                [self.delegate popSelectedApartment:newApartment];
                [self.navigationController popViewControllerAnimated:YES];
            }
        }
    }]];
    [self presentViewController:alert animated:YES completion:nil];
}

- (void)rightBarButtonItemEvent:(id)sender{
    if (selectedApartment) {
        if ([self.delegate respondsToSelector:@selector(popSelectedApartment:)]) {
            [self.delegate popSelectedApartment:selectedApartment];
            [self.navigationController popViewControllerAnimated:YES];
        }
    }else{
        NSString *apartmentShowName = [YWLoginTool apartmentShowName];
        [YWCommonTool showTextHUDWithContent:[NSString stringWithFormat:@"%@%@",NSLocalizedString(@"pleaseSelectOne", nil),apartmentShowName.length?apartmentShowName:NSLocalizedString(@"apartment", nil)]];
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
